import * as echarts from 'echarts'
import { ref, onMounted, onUnmounted, watch, Ref, ComputedRef } from 'vue'

// 数据接口定义
interface ChartData {
  values: number[]
}

interface Options {
  maxPoints?: number
  chartName?: string
  smooth?: boolean
}

/**
 * 实时滚动折线图 Hook
 * @param chartRef 图表容器的 ref（必须是 Ref 类型）
 * @param data 响应式数据源
 * @param options 配置项
 */
export function useRealtimeLineChart(
  chartRef: Ref<HTMLDivElement | null>,
  data: ComputedRef<ChartData | null>,
  options: Options = {}
) {
  const {
    maxPoints = 50,
    chartName = '实时趋势图',
    smooth = true,
  } = options

  let chartInstance: echarts.ECharts | null = null
  const timestamps = ref<string[]>([]) // 时间戳队列
  const allValues = ref<number[][]>([])     // 每根钢丝绳的历史值（二维数组）

  let isInitialized = false

  function initChart() {
    if (isInitialized || !chartRef.value || !data.value) return
    timestamps.value = [];
    allValues.value = [];

    const seriesData = (data.value?.values || []).map((_, index) => ({
      name: `绳${index + 1}`,
      type: 'line',
      data: [],
      // smooth,
      showSymbol: false,
      // color: colors[index % colors.length]
      emphasis: { // 确保悬停时显示
        focus: 'series'
      }
    }))

    if (!chartInstance) {
      chartInstance = echarts.init(chartRef.value!)
    }

    chartInstance.setOption({
      title: { text: chartName },
      tooltip: { trigger: 'axis', triggerOn: 'click' },
      legend: {
        data: (data.value?.values || []).map((_, i) => `绳${i + 1}`),
        // bottom: 0
      },
      toolbox: {
        feature: {
          dataView: {},
          saveAsImage: {}
        }
      },
      xAxis: {
        type: 'category',
        data: [],
        boundaryGap: false,
        // splitLine: {
        //   show: true
        // }
      },
      yAxis: {
        type: 'value',
        axisLine: {
          show: true // 显示纵轴轴线
        }
      },
      grid: { left: '5%', right: '5%', bottom: '12%', top: '10%' },
      series: seriesData,                
      dataZoom: [
        {
          type: 'slider', // 使用滑块式滚动条
          xAxisIndex: 0,
          filterMode: 'filter', 
          realtime: true,
          brushSelect: false,
          // borderColor: 'transparnt',
          height: 25,
          handleSize: 36,
          handleStyle: {
            color: '#3398DB',
            borderWidth: 0,
          },
          fillerColor: '#3398DB',
          showDataShadow: false,
          showDetail: false,
        },
        {
          type: 'inside'
        }
      ]
    })

    // 初始完成后主动调用一次 resize，确保尺寸正确
    nextTick(() => {
      chartInstance?.resize()
    })

    isInitialized = true
  }

  function updateChart() {
    if (!chartInstance || !data.value) return

    const currentValues = data.value.values
    const now = new Date()
    const timeStr = now.toLocaleTimeString() + `.${now.getMilliseconds().toString().padStart(3, '0')}`
    timestamps.value.push(timeStr)

    // 初始化每根钢丝绳的数据队列
    for (let i = 0; i < currentValues.length; i++) {
      allValues.value[i] = allValues.value[i] ?? []
      allValues.value[i].push(currentValues[i])
    }

    const option = chartInstance!.getOption()

    // 更新系列数据
    for (let i = 0; i < currentValues.length; i++) {
      option.series[i].data = allValues.value[i]
    }

    chartInstance!.setOption({
      xAxis: {
        data: timestamps.value
      },
      series: option.series,
    })

    chartInstance!.dispatchAction({
      type: 'dataZoom',
      dataZoomIndex: 0,
      startValue: Math.max(0, timestamps.value.length - maxPoints),
      endValue: timestamps.value.length - 1
    })
  }

  function clearChart() {
    if (chartInstance) {
      const option = chartInstance.getOption()
      option.series.forEach(s => s.data = [])
      timestamps.value = []

      chartInstance.setOption({
        xAxis: { data: [] },
        series: option.series,
        legend: {
          data: []
        },
        dataZoom: {
          type: 'slider',
          start: 0
        }
      })
    }
    isInitialized = false
  }

  // 监听 chartRef 和 data 是否都就绪
  // const stopWatch = watch(
  //   () => [chartRef.value, data.value],
  //   ([newChartRef, newData]) => {
  //     if (newChartRef && newData?.values?.length > 0 && !isInitialized) {
  //       // 延迟执行一次，确保 DOM 已经渲染完成
  //       setTimeout(() => {
  //         initChart()
  //         updateChart()
  //       }, 50)
  //       stopWatch()
  //     }
  //   },
  //   { deep: true, immediate: true }
  // )

  // 后续数据变化只触发更新
  const stopWatch = watch(
    () => data.value?.values,
    (newValues) => {
      if (newValues && newValues.length > 0) {
        // if (!isInitialized) return
        if (!isInitialized) {
          initChart()
        }
        updateChart()
      }
    },
    { deep: true, immediate: true }
  )

  // 窗口大小变化处理
  function handleResize() {
    if (chartInstance) {
      // 显式调用 resize，并传入新的宽高
      const chartDom = chartRef.value
      if (chartDom) {
        chartInstance!.resize({
          width: chartDom.clientWidth,
          height: chartDom.clientHeight
        })
      }
    }
  }

  onMounted(() => {
    window.addEventListener('resize', handleResize)
  })

  onUnmounted(() => {
    window.removeEventListener('resize', handleResize)
    if (chartInstance) {
      chartInstance.dispose()
      chartInstance = null
    }
    stopWatch()
  })

  return {
    clearChart,
  }
}